import AttributePoolAPI from '@/api/AttributePool';
import {
  Box,
  ClickModal,
  FieldCols,
  FieldEffect,
  Icon,
  mapField,
  PaginationTable,
  SearchFields,
  useCall,
  useFieldCtx,
  useFormValue,
  usePaginationCommon,
  usePubSub,
} from '@/components';
import { ATTRIBUTE_TYPES_MAP } from '@/constants/attributePool';
import { CompanySearchField, CompanySelectField, useCompanyOptions } from '@/pages/components';
import { attributeRequestMap } from '@/pages/data/AttributePool/components/shared';
import { commonRules, enumToOptions, forkHandler, wait } from '@/utils';
import { Button, Form, message, Tooltip } from 'antd';
import React, { useEffect, useMemo } from 'react';
import AttributeAsyncSourceSelect from './components/AttributeAsyncSourceSelect';
import AttributeDictionaryField from './components/AttributeDictionaryField';

const editFields = [
  ['attributeCode', '属性编码', null, { required: true, rules: [...commonRules.code] }],
  ['attributeName', '属性名称', null, { required: true }],
  ['attributeImportType', '输入类型', 'select', { required: true, options: enumToOptions(ATTRIBUTE_TYPES_MAP) }],
  ['attributeType', '属性类别', null, { required: true }],
  // [
  //   'companyCode',
  //   '保险公司',
  //   (props) => {
  //     const form = useFieldCtx('form');
  //     const options = useCompanyOptions();
  //     const { value } = props;
  //     useEffect(() => {
  //       const companyName = options.find((v) => `${v.value}` === `${value}`)?.label || '通用';
  //       form.setFieldsValue({ companyName });
  //     }, [value, options]);

  //     return <CompanySelectField {...props} />;
  //   },
  //   { required: true, initialValue: '0' },
  // ],
  ['companyName', null, 'hidden', { colProps: { xs: 0 } }],
  [
    'attributeSource',
    '字典数据源',
    AttributeAsyncSourceSelect,
    {
      initialValue: null,
      preserve: false,
      getColProps(item, index, form) {
        return {
          hidden: useFormValue(form, 'companyCode', (v) => `${v}` === '0'),
        };
      },
    },
  ],

  [
    'attributeValueSpecs',
    '属性规则',
    null,
    {
      rules: [
        {
          validator: (rule, value) =>
            new Promise((res, rej) => {
              try {
                if (value) new RegExp(value);
                res();
              } catch (e) {
                rej(e);
              }
            }),
          message: '不是有效的正则语句',
        },
      ],
    },
  ],
  ['attributeRemark', '备注'],
  [
    'attributeDictionary',
    '字典:',
    AttributeDictionaryField,
    {
      colon: false,
      rules: [
        {
          async validator(rule, value) {
            await wait(1e3);
            value && JSON.parse(value);
          },
          message: '请输入有效的JSON格式',
        },
      ],
      colProps: { xs: 24, md: 24 },
      getItemProps(item, index, form) {
        const attributeSource = useFormValue(form, 'attributeSource');
        const show = !!attributeSource;
        const onFetch = useCall(() => {
          attributeRequestMap[attributeSource]?.(form);
        });

        const label = useMemo(
          () => (
            <>
              字典 :
              {show && (
                <>
                  <Box px={1} />
                  <Button size='small' onClick={onFetch}>
                    获取字典数据
                  </Button>
                </>
              )}
            </>
          ),
          [show],
        );

        return { label };
      },
      initialValue: `[
  {
    "code": "",
    "name": ""
  }
]`,
      itemProps: { labelAlign: 'left', labelCol: { flex: '100%' }, wrapperCol: { flex: '100%' } },
    },
  ],
].map(mapField);

function EditModal({ item = null, ...props }) {
  const [form] = Form.useForm();
  const content = (
    <Form form={form}>
      <FieldEffect name='id' />
      <FieldCols form={form} fields={editFields} colProps={{ xs: 12 }} />
    </Form>
  );

  const onToggle = useCall((open) => {
    if (open) {
      if (item) {
        if (item.attributeDictionary) {
          item.attributeDictionary = JSON.stringify(JSON.parse(item.attributeDictionary), null, 2);
        }
        form.setFieldsValue(item);
      } else {
        form.resetFields();
      }
    }
  });

  const onOk = useCall(async () => {
    const data = await form.validateFields();
    if (data.attributeDictionary) {
      data.attributeDictionary = JSON.stringify(JSON.parse(data.attributeDictionary));
    }
    await AttributePoolAPI.insertOrUpdate(data);
    message.success('保存成功');
    return props?.onOk?.(data);
  });

  const title = useFormValue(form, 'id', (v) => (v ? '编辑属性' : '新增属性'));

  return <ClickModal title={title} {...props} content={content} onOk={onOk} onToggle={onToggle} />;
}

const columns = [
  // {
  //   dataIndex: 'companyName',
  //   title: '保险公司',
  // },
  {
    dataIndex: 'attributeCode',
    title: '属性编码',
  },
  {
    dataIndex: 'attributeName',
    title: '属性名称',
  },
  {
    dataIndex: 'attributeImportType',
    title: '输入类型',
    map: ATTRIBUTE_TYPES_MAP,
  },
];

const actions = {
  edit: {
    dialog: EditModal,
    text: (
      <Button size='small' type='text'>
        <Icon type='edit' />
      </Button>
    ),
    itemProp: 'item',
  },
  del: {
    confirm: '确认删除此属性吗?',
    text: (
      <Button size='small' type='text'>
        <Icon type='delete' />
      </Button>
    ),
    onOk: (row) => AttributePoolAPI.remove(row.id, ''),
  },
  delByCode: {
    confirm: '确认删除与当前相同Code的属性吗?',
    text: (
      <Tooltip placement='top' trigger='hover' title='删除相同Code'>
        <Button size='small' type='text'>
          <Icon type='clear' />
        </Button>
      </Tooltip>
    ),
    onOk: (row) => AttributePoolAPI.remove(row.id, row.attributeCode),
  },
};

const searchFields = [
  [['t', 'attributeCode'], '属性编码'],
  [['t', 'attributeName'], '属性名称'],
  // [['t', 'companyName'], '保险公司', CompanySearchField],
].map(mapField);

function AttributePoolManage(props) {
  const { tableRef, searchData, onSearch, onSelect, selectedRef, reset } = usePaginationCommon();

  const onBatchDel = useCall(forkHandler(() => AttributePoolAPI.remove(selectedRef.current), reset, true));

  return (
    <>
      <SearchFields fields={searchFields} onSubmit={onSearch} onReset={onSearch} />

      <Box flex dir='row' jus='between' py={1}>
        {/*<PopoverConfirm onOk={onBatchDel}>
         <Button>批量删除</Button>
         </PopoverConfirm>*/}
        <div />
        <EditModal onOk={reset}>
          <Button type='primary'>+新增属性</Button>
        </EditModal>
      </Box>
      <PaginationTable
        ref={tableRef}
        service={AttributePoolAPI.findByPage}
        serviceData={searchData}
        columns={columns}
        actions={actions}
        onAfterEdit={reset}
        onAfterDel={reset}
        onAfterDelByCode={reset}
        actionCol={{ width: 100 }}
      /*rowSelection={{
        onChange: onSelect,
      }}*/
      />
    </>
  );
}

export default AttributePoolManage;
